package com.safe.first.infrastructure.config;

import com.safe.first.infrastructure.interceptor.*;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter;

/**
 * @author Mickey
 * @since 2022/6/10
 **/
@Configurable
@EnableWebSecurity
@AllArgsConstructor
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    private final MySecurityContextRepository securityContextRepository;
    private final MyHttp403ForbiddenEntryPoint http403ForbiddenEntryPoint;
    private final MyFilterSecurityInterceptor filterSecurityInterceptor;
    private final MyAccessDeniedHandlerImpl accessDeniedHandler;
    private final CompositeTokenAuthenticationFilter compositeTokenAuthenticationFilter;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) {

    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .requestCache().disable()
                .sessionManagement().disable()
                .logout().disable()
                .formLogin().disable()
                .exceptionHandling()
                .accessDeniedHandler(accessDeniedHandler)
                .authenticationEntryPoint(http403ForbiddenEntryPoint)
                .and()
                .securityContext()
                .securityContextRepository(securityContextRepository)
                .and()
                .addFilterBefore(new TraceLogProcessFilter(), WebAsyncManagerIntegrationFilter.class)
                .addFilterAt(compositeTokenAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
                .addFilterAt(filterSecurityInterceptor, FilterSecurityInterceptor.class);
    }

}

